<template>
  <div class="g-page-container">
    <PageHeader title="潜客维护" />
    <div class="g-content-container">
      <CustomerSearchForm
        ref="search-form"
        @search="searchLoadTableList"
        @export="exportFile"
      />

      <ButtonGroup :options="middleButtons" @click="handleButtonClick" />
      <MainTableList
        :loading="loading"
        :data-source="dataSource"
        :columns="columns"
        slot-name="serialNumber"
        :row-selection="rowSelectionMixin"
        :pagination="paginationMixin"
        @change="handleTableChange"
        @number-click="handleNumberClick"
      />
    </div>
    <component
      :is="currentComponent"
      :visible.sync="visibleDrawer"
      :price-id="priceId"
      :process-id="processId"
      :detail="formData"
      @showEdit="changeEdit"
      @fresh="loadTableList"
    />
    <DrawerEditCustomer
      :visible.sync="showEdit"
      :price-id="priceId"
      @fresh="loadTableList"
    />
  </div>
</template>

<script>
import CustomerSearchForm from './components/customerSearchForm.vue';
import mixinTable from '@/mixins/mixin-table.js';
import mixinPublic from './components/mixin';

import MainTableList from './components/mainTableList.vue';
import ButtonGroup from './components/buttonGroup.vue';
import DrawerEditCustomer from './components/DrawerEditCustomer.vue';
import DrawerMaintainDetail from './components/DrawerMaintainDetail.vue';

import {
  postCustomerFormalByPage,
  postCustomerMainUpdate,
} from '@/api/customerMaintain.js';
import monent from 'moment';
import { CUSTOMER_NODE } from '@/constants/index';

export default {
  components: {
    CustomerSearchForm,
    MainTableList,
    ButtonGroup,
    DrawerEditCustomer,
    DrawerMaintainDetail,
  },
  mixins: [mixinTable, mixinPublic],
  data() {
    return {
      showEdit: false,
      formData: {},
      currentComponent: '',
      asc: true,
      loading: false,
      dataSource: [],
      filedsKeys: [],
      exportData: [],
      dateNeedList: [],
      isDateChange: false,
      currentNode: CUSTOMER_NODE[1],
      columnKey: '',
      visibleDrawer: false,
      priceId: undefined,
      processId: undefined,
      formInfo: {},
    };
  },
  computed: {
    middleButtons() {
      return [
        {
          key: 'retweet',
          label: '转为正式客户',
          type: 'primary',
          icon: 'retweet',
          authKey: 'customer-button-main-transfer',
        },
      ];
    },

    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          dataIndex: 'dataIndex',
          width: 30,
          required: true,
          customRender: (t, r, index) => {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '客户编号',
          dataIndex: 'code',
          key: 'code',
          width: 120,
          sorter: true,
          required: true,
          scopedSlots: { customRender: 'serialNumber' },
        },
        {
          align: 'center',
          title: '客户名称',
          dataIndex: 'customerName',
          key: 'customerName',
          width: 120,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '客户简称',
          dataIndex: 'name',
          key: 'name',
          width: 60,
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '客户分类',
          dataIndex: 'classificationCode',
          key: 'classificationCode',
          width: 80,
          sorter: true,
          ellipsis: true,
          customRender: (text) => this.escapeCustomerType[text],
        },
        {
          align: 'center',
          title: '销售组织',
          dataIndex: 'salesOrgCode',
          key: 'salesOrgCode',
          width: 60,
          sorter: true,
          ellipsis: true,
          customRender: (text) => this.escapeSalesOrgCode[text],
        },
        {
          align: 'center',
          title: '销售组',
          dataIndex: 'salesGroupCode',
          key: 'salesGroupCode',
          width: 100,
          sorter: true,
          ellipsis: true,
          customRender: (value, row, index) => {
            value = value.split(',');
            let data = this.getltcoledList || {};
            let info = value?.map((item) => {
              return data[item];
            });
            return info.join('，');
          },
        },
        {
          align: 'center',
          title: 'KAPM组',
          width: 100,
          dataIndex: 'pmGroupCode',
          key: 'pmGroupCode',
          sorter: true,
          ellipsis: true,
          customRender: (value, row, index) => {
            value = value.split(',');
            let data = this.getltcoledList || {};
            let info = value?.map((item) => {
              return data[item];
            });
            return info.join('，');
          },
        },
        {
          align: 'center',
          title: '创建人',
          width: 60,
          dataIndex: 'createUserName',
          key: 'createUserName',
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '创建时间',
          width: 100,
          dataIndex: 'createTime',
          key: 'createTime',
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '最后修改人',
          width: 60,
          dataIndex: 'updateUserName',
          key: 'updateUserName',
          sorter: true,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '最后修改时间',
          width: 100,
          dataIndex: 'updateTime',
          key: 'updateTime',
          sorter: true,
          ellipsis: true,
        },
      ];
      return columns;
    },
    escapeSalesOrgCode() {
      return (
        this.$store.getters.getOrg({
          code: 'ltcsmsizebu',
          isDict: true,
        }) || {}
      );
    },
    escapeCustomerType() {
      return this.$store.state.dictionary.dict['customer_type'] || {};
    },
    getltcoledList() {
      const list1 = this.$store.getters.getOrg({
        code: 'ltcorgoled',
        type: 'sales',
        isDict: true,
      });
      const list2 = this.$store.getters.getOrg({
        code: 'ltcorgltps',
        type: 'sales',
        isDict: true,
      });
      const list3 = this.$store.getters.getOrg({
        code: 'ltcorgoled',
        type: 'kapm',
        isDict: true,
      });
      const list4 = this.$store.getters.getOrg({
        code: 'ltcorgltps',
        type: 'kapm',
        isDict: true,
      });
      return { ...list1, ...list2, ...list3, ...list4 };
    },
  },
  created() {
    this.getCustomerFormalByPage();
  },
  // beforeRouteEnter(to, from, next) {
  //   next(vm => {
  //     if (to.query?.id) {
  //       vm.handleNumberClick(to.query);
  //     }
  //   });
  // },
  methods: {
    changeEdit(id) {
      this.priceId = id;
      this.showEdit = true;
    },
    handleSelectFileds(filedsKeys) {
      this.filedsKeys = filedsKeys;
    },
    async getCustomerFormalByPage() {
      let data = this.$refs['search-form']?.getSearchParams;
      this.loading = true;
      try {
        const res = await postCustomerFormalByPage({
          ...data,
          isSubmersible: false,
        });
        let dataList = res?.data?.data?.records;
        this.dataSource = dataList || [];
        this.paginationMixin.total = res?.data?.data?.total;
        this.loading = false;
      } catch (err) {
        console.log(err, 'err');
        this.loading = false;
      }
    },
    async handleNumberClick(record) {
      // let currentNode = CUSTOMER_NODE[Number(record.nodeCode)];
      // if (!currentNode) {
      //   this.$message.error('非有效节点，无法进入！');
      //   return;
      // }
      // if (record.nodeCode === '1') {
      //   const res = await getCustomerMainDetail(record.id)
      //   const isCurrentProcessor = res?.data?.data?.isCurrentProcessor
      //   if (isCurrentProcessor) {
      //     this.currentNode = CUSTOMER_NODE[Number(record.nodeCode)];
      //   } else {
      //     this.currentNode = CUSTOMER_NODE[Number(5)];
      //   }

      // } else if (record.nodeCode === '6') {
      //   this.currentNode = CUSTOMER_NODE[Number(record.nodeCode)];
      // } else {
      //   this.currentNode = CUSTOMER_NODE[Number(record.nodeCode)];
      // }
      this.currentComponent = 'DrawerMaintainDetail';
      this.processId = record.processId;
      this.priceId = record.id;
      this.visibleDrawer = true;
      console.log(this.currentComponent);
    },
    searchLoadTableList() {
      this.paginationMixin.current = 1;
      this.loadTableList();
    },
    getSearchForm() {
      const form = this.$refs['search-form']?.getSearchParams || {};
      let { startCreateTime, endCreateTime } = form;
      form.startCreateTime = startCreateTime
        ? `${monent(startCreateTime).format('YYYY-MM-DD')} 00:00:00`
        : '';
      form.endCreateTime = endCreateTime
        ? `${monent(endCreateTime).format('YYYY-MM-DD')} 23:59:59`
        : '';
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
        column: this.columnKey,
      };
      return { ...form, ...page };
    },
    async loadTableList() {
      let formData = this.getSearchForm();
      // 校验时间是否只输入一个
      if (!formData.startCreateTime && formData.endCreateTime) {
        this.$message.error('请选择开始时间');
        return;
      }
      if (formData.startCreateTime && !formData.endCreateTime) {
        this.$message.error('请选择结束时间');
        return;
      }
      this.loading = true;
      const result = await postCustomerFormalByPage({
        ...formData,
        isSubmersible: false,
      }).finally(() => (this.loading = false));
      this.paginationMixin.total = result?.data?.data?.total || 0;
      this.dataSource = result?.data?.data?.records || [];
    },
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      // console.log(page,sorter);
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.loadTableList();
    },
    handleButtonClick(key) {
      // console.log(key);
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    addCallback() {
      this.currentComponent = 'DrawerAddCustomer';
      this.visibleDrawer = true;
    },
    async retweetCallback() {
      const ids = this.rowSelectionMixin.selectedRowKeys || [];
      let idArr = ids?.map((item) => {
        return {
          id: item,
          isSubmersible: true,
        };
      });
      if (!ids.length) {
        this.$message.info('请先选择数据！');
        return;
      }
      console.log(idArr);
      try {
        this.$confirm(
          '确认转为正式客户？转为正式客户后，请通过【客户管理】->【客户信息】菜单查询该客户的详情。',
          '转为正式客户确认',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(async () => {
            let res = await postCustomerMainUpdate(idArr);
            if (res?.data?.code === 0) {
              this.$message.success('转正式客户成功');
              this.loadTableList();
            } else {
              this.$message.error('转正式客户失败');
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } catch (error) {
        // console.log('error: ', error);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.table-container {
  padding: 15px 20px;
  height: calc(100vh - 160px);
  box-sizing: border-box;
}
</style>
